package com.lagou.demo.interceptor;

import com.lagou.edu.mvcframework.annotations.LagouInterceptor;
import com.lagou.edu.mvcframework.annotations.LagouSecurity;
import com.lagou.edu.mvcframework.interceptor.HandleInterceptor;
import com.lagou.edu.mvcframework.pojo.Handler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@LagouInterceptor(1)
public class SecurityInterceptor implements HandleInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Handler handler) throws Exception {
        LagouSecurity handleSecurity = handler.getMethod().getAnnotation(LagouSecurity.class);
        //如果存在权限的注解
        if (handleSecurity != null){
            String userName = request.getParameter("username");
            String[] userNameList = handleSecurity.value();
            if (Arrays.asList(userNameList).contains(userName)){
                return true;
            }else {
                response.getWriter().write("not access permission");
                return false;
            }
        }else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Handler handler) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Handler handler) {

    }
}
